package net.tv90.shoppingserver.aop;

import cn.dev33.satoken.exception.NotLoginException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import net.tv90.shoppingserver.exception.ServerException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@ControllerAdvice(annotations = Controller.class)
public class GlobalExceptionHandler {

    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ModelAndView handleNotLoginException(NotLoginException ex, Model model) {
        model.addAttribute("errorMsg", "用户未登录，请登录后访问");
        log.info("用户已被拦截，" + ex.getMessage());
        ModelAndView mv = new ModelAndView();
        mv.setViewName("login");
        return mv;
    }

    @ExceptionHandler(ServerException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public String handleServerException(ServerException ex, Model model) {
        model.addAttribute("errorMsg", ex.getMessage());
        model.addAttribute("code", ex.getStatus());
        // 获取当前请求的 HttpServletRequest
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        // 重定向到当前页面
        return "redirect:" + request.getRequestURI();
    }
}